/*
  https://next.vuex.vuejs.org/zh/guide/actions.html
  Action 提交的是 mutation，而不是直接变更状态。
  Action 可以包含任意异步操作。
 */

import { asyncAndCommit } from "@/services";

// 获取专栏列表
export function fetchColumns({ state, commit }) {
  return asyncAndCommit(
    `api/columns?currentPage=${1}&pageSize=${6}`,
    "fetchColumns",
    commit
  );
}

// 获取专栏详情
export function fetchColumn({ state, commit }, id) {
  return asyncAndCommit(`api/columns/${id}`, "fetchColumn", commit);
}

// 登录
export function login({ commit }, payload) {
  return asyncAndCommit("api/user/login", "login", commit, {
    method: "post",
    data: payload,
  });
}

// 获取用户信息
export function fetchCurrentUser({ commit }) {
  return asyncAndCommit("api/user/current", "fetchCurrentUser", commit);
}

// 组合 Action https://next.vuex.vuejs.org/guide/actions.html#composing-actions
export function loginAndFetch({ dispatch }, payload) {
  return dispatch("login", payload).then(() => {
    return dispatch("fetchCurrentUser");
  });
}

// 新建一篇文章
export function createPost({ commit }, payload) {
  return asyncAndCommit("api/posts", "createPost", commit, {
    method: "post",
    data: payload,
  });
}

// 删除单个文章
export function deletePost({ commit }, id) {
  return asyncAndCommit(`api/posts/${id}`, "deletePost", commit, {
    method: "delete",
  });
}

// 获得单个文章
// export function fetchPost() {}

// 更新单个文章
// export function updatePost() {}

// 获得属于专栏的文章列表
// export function fetchPosts({ state, commit }, id) {}
